package com.zhoug.common3.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.zip.GZIPInputStream;

/**
 * @Author: zhoug
 * @Date: 2022/10/17
 * @Description:
 */
public class GZipHelper {
    private static final String TAG = ">>>GZipHelper";

    /**
     * 解压.net GZip 压缩的数据
     *
     * @param bytes       .net GZipStream 压缩后的字节数据
     * @param charsetName 编码方式
     */
    public static String unZipOnNet(byte[] bytes, String charsetName) {

        InputStream inputStream = null;
        ByteArrayOutputStream out = null;
        GZIPInputStream gzip = null;
        try {
            ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
            byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
            byte[] resultByte = byteBuffer.array();
            LogUtils.d(TAG, "resultByteArray:resultByte size :" + resultByte.length);
            inputStream = new ByteArrayInputStream(resultByte);
            out = new ByteArrayOutputStream();
            gzip = new GZIPInputStream(inputStream);
            byte[] buffer = new byte[1024];
            int n = 0;
            while ((n = gzip.read(buffer, 0, buffer.length)) > 0) {
                out.write(buffer, 0, n);
            }
            String s = out.toString(charsetName);
            LogUtils.d(TAG, "resultByteArray:s=" + s);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(gzip);
            IOUtils.close(inputStream);
            IOUtils.close(out);
        }
        return null;
    }

    public static String unZipOnNet(byte[] bytes) {
        return unZipOnNet(bytes, "UTF-8");
    }

}
